from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from app.models.system import SysRole, SysUserRole


class UserRoleService:
    def __init__(self, session: AsyncSession):
        self.session = session

    async def get_role_by_id(self, role_id: int):
        stmt = select(SysRole).where(SysRole.id == role_id)
        result = await self.session.execute(stmt)
        return result.scalar_one_or_none()

    async def save_user_roles(self, user_id: int, role_ids: list[int], is_commit: bool = True):
        # 实现用户角色关联的保存逻辑
        stmt = select(SysUserRole).where(SysUserRole.user_id == user_id)
        result = await self.session.execute(stmt)
        existing_roles = result.scalars().all()
        existing_role_ids = [role.role_id for role in existing_roles]
        # 新增角色
        for role_id in role_ids:
            if role_id not in existing_role_ids:
                new_role = SysUserRole(user_id=user_id, role_id=role_id)
                self.session.add(new_role)
        # 删除角色
        for role in existing_roles:
            if role.role_id not in role_ids:
                self.session.delete(role)

        if is_commit:
            await self.session.commit()
